package sdkshell.kuaiyan.com.kuaiyansdk.http;

import com.wmcsk.dl.util.LogUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import sdkshell.kuaiyan.com.kuaiyansdk.SdkInit;
import sdkshell.kuaiyan.com.kuaiyansdk.http.Ihttp.NetBuilderConfig;
import sdkshell.kuaiyan.com.kuaiyansdk.http.callback.DownloadCallBack;
import sdkshell.kuaiyan.com.kuaiyansdk.http.callback.ResultCallback;
import sdkshell.kuaiyan.com.kuaiyansdk.listener.HttpGetInterface;
import sdkshell.kuaiyan.com.kuaiyansdk.util.IOUtils;
import sdkshell.kuaiyan.com.kuaiyansdk.util.StringUtils;

/**
 * Created by admin on 2016/8/29.
 */
public class HttpGetSend implements HttpGetInterface {
    public HttpGetSend() {
        super();
    }

    @Override
    public void getData(NetBuilderConfig config, Map<String, String> params, ResultCallback callback, String url) {
        Thread thread = new Thread(new GetTask(new WeakReference<HttpGetSend>(this), callback, config));
        thread.start();
//        Executors.newSingleThreadExecutor().execute();
    }

    static class GetTask implements Runnable {
        private WeakReference<HttpGetSend> getSendWeakReference;
        private ResultCallback callback;
        private NetBuilderConfig config;

        public GetTask(WeakReference<HttpGetSend> getSendWeakReference, ResultCallback callback, NetBuilderConfig config) {
            this.getSendWeakReference = getSendWeakReference;
            this.callback = callback;
            this.config = config;
        }

        @Override
        public void run() {
            if (getSendWeakReference != null) {
                HttpGetSend httpGetSend = getSendWeakReference.get();
                if (httpGetSend != null) {
                    httpGetSend.SendMessage(config, callback);
                }
            }
        }
    }


    private void SendMessage(NetBuilderConfig config, final ResultCallback callback) {
        String url = config.getNetConfig().getUrl();
        if (config.getNetConfig().getContent() != null) {
            url = url + config.getNetConfig().getContent();
        } else {
            url = StringUtils.getUrlFromUrlAndParams(url, config.getNetConfig().getParams()).toString();
        }
        try {
            boolean isImage = config.getNetConfig().isImage();
            sendMessage(url, callback, isImage,config);
        } catch (final Exception e) {
            e.printStackTrace();
            SdkInit.getUiHandle().post(new Runnable() {
                @Override
                public void run() {
                    if (callback != null) {
                        callback.onError(e, e.getMessage());
                    }
                }
            });
        }
    }

    private void sendMessage(String url, final ResultCallback callback, boolean isImage, NetBuilderConfig netBuilderConfig) throws Exception {
        String urlPath = url;
        URL urls = new URL(urlPath);
        // 连接
        HttpURLConnection conn = (HttpURLConnection) urls
                .openConnection();
        conn.setRequestMethod("GET");
        conn.setReadTimeout(5000);
        // 响应结果
        final StringBuilder results = new StringBuilder();
        final int code = conn.getResponseCode();
        if (200 == code) {
            InputStream input = conn.getInputStream();
            if(!netBuilderConfig.getNetConfig().isDownload()) {
                String encoding = netBuilderConfig.getNetConfig().getEncoding();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input, encoding));
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    results.append(line);
                }
                SdkInit.getUiHandle().post(new Runnable() {
                    @Override
                    public void run() {
                        Object o = null;
                        if (callback != null) {
                            callback.onResponse(o, results.toString());
                        }
                    }
                });
            }else{
                BufferedInputStream bufferedInputStream = new BufferedInputStream(input);
                String desPath = netBuilderConfig.getNetConfig().getDownloadPath();
                final File desFile = new File(desPath);
                if(!desFile.getParentFile().exists()){
                    desFile.getParentFile().mkdirs();
                }
                if(!desFile.exists()){
                    desFile.createNewFile();
                }
                BufferedOutputStream bufferedOutputStream = null ;
                try{
                    bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(desFile)) ;
                    byte buffer[] = new byte[1024];
                    int len = -1;
                    while((len = bufferedInputStream.read(buffer))!=-1){
                        bufferedOutputStream.write(buffer,0,len);
                    }
                    bufferedOutputStream.flush();
                    SdkInit.getUiHandle().post(new Runnable() {
                        @Override
                        public void run() {
                            if (callback != null&&callback instanceof DownloadCallBack) {
                                DownloadCallBack downloadCallBack = (DownloadCallBack) callback;
                                downloadCallBack.downloadOk(desFile.getAbsolutePath());
                            }
                        }
                    });
                }finally {
                    IOUtils.closeQuietly(bufferedOutputStream);
                    IOUtils.closeQuietly(bufferedInputStream);
                }
            }
        }else{
            SdkInit.getUiHandle().post(new Runnable() {
                @Override
                public void run() {
                    if(callback!=null){
                        RuntimeException e = new RuntimeException("网络请求失败HttpGetSend"+code);
                        callback.onError(e,e.getMessage());
                    }
                }
            });
            LogUtils.getNewInstance("HttpGetSend").eob("网络请求失败"+code);
        }
    }
}
